
// https://db.xiaoyuzhishi.com/api/managements/entities
//     获取所有实体名称列表
// https://db.xiaoyuzhishi.com/api/managements/entities/{EntityName}/fields
//     获取某个实体的字段列表
// 比如：
// https://db.xiaoyuzhishi.com/api/managements/entities/TreatmentSession/fields
//     就能得到诊疗session的字段列表


const rootUrl = 'https://mindliv-cn.com'  //'http://47.105.164.163' //https://db.xiaoyuzhishi.com'
let Authorization = null
const request = (url ,config)=>{
    return new Promise((resolve, reject)=>{
        if(!config.headers){
            config.headers = {}
        }
        if(Authorization){
            config.headers['Authorization'] = 'Bearer '+ Authorization
        }
        fetch(rootUrl + url, config)
            .then((response) => {
                // 先读取原始响应文本（无论类型，统一先获取文本）
                return response.text().then(text => {
                    // 保存响应状态和文本，供后续处理
                    return {
                        ok: response.ok,
                        status: response.status,
                        text: text,
                        contentType: response.headers.get('content-type')
                    };
                });
            })
            .then(({ ok, status, text, contentType }) => {
                // 尝试解析JSON（无论Content-Type是否为JSON）
                let result;
                const isJsonType = contentType && contentType.includes('application/json');

                try {
                    // 只有当内容看起来像JSON时才尝试解析（避免纯文本解析报错）
                    if (isJsonType || (text.trim().startsWith('{') && text.trim().endsWith('}')) ||
                        (text.trim().startsWith('[') && text.trim().endsWith(']'))) {
                        result = JSON.parse(text);
                    } else {
                        // 不符合JSON格式特征，直接返回文本
                        result = text;
                    }
                } catch (e) {
                    // 解析失败：即使Content-Type标为JSON，也回退到文本
                    console.warn('JSON解析失败，回退到文本处理:', e);
                    result = text;
                }

                // 处理响应状态
                if (ok) {
                    return result; // 成功响应，返回解析结果（JSON或文本）
                } else {
                    // 错误响应：包装成统一格式（优先取解析后的msg，否则用原始文本）
                    const error = {
                        status,
                        msg: (typeof result === 'object' && result.msg) ? result.msg : text || `请求失败（状态码：${status}）`
                    };
                    throw error;
                }
            })
            .then((result) => {
                resolve(result);
            })
            .catch((error) => {
                console.error('Fetch error:', error);
                if (error.status === 401) {
                    ELEMENT.Message.error(error.msg || '认证失败，请重新登录');
                    sessionStorage.clear();
                    window.location.reload();
                } else {
                    ELEMENT.Message.error(error.msg || '请求失败，请稍后重试');
                }
                reject(error);
            })
    })
}



class Section {
    constructor() {
        this.body = {}
        this.bodys = []

        this.defaultList = [
            {
                sessionId:1,
                stepList:[
                    {
                        src:'detail/anquangan.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'安全感'
            },
            {
                sessionId:1,
                stepList:[
                    {
                        src:'./detail/zhuannian.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'转念'
            },
            {
                sessionId:1,
                stepList:[
                    {
                        src:'./detail/fangxiazhinian.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'放下执念'
            },
            {
                sessionId:2,
                stepList:[
                    {
                        src:'./detail/guiyuanmamasenlin.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'森林舒压'
            },
            {
                sessionId:2,
                stepList:[
                    {
                        src:'./detail/mengchongzhiyu.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'萌宠治愈'
            },
            {
                sessionId:2,
                stepList:[
                    {
                        src:'./detail/chonghuimuti.ogg',
                        type:'content'
                    },
                    {
                        src:'',
                        type:'control',
                        controlType: 'click',
                        timeout: 6000
                    }
                ],
                name:'重回母体'
            }
        ]
    }

    uploadAudio(body){

        return request('/api/audios',{
            method: 'post',
            body
        })
    }

    create(body){
        return request('/api/sections',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body
        })
    }

    delete(id){
        return request('/api/sections/'+id,{
            method: 'delete',
            headers:{
                'Content-Type':'application/json'
            }
        })
    }

    update(body){
        let id = body.id
        delete body.id
        return request('/api/sections/'+id,{
            method: 'PATCH',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    getList(filter){
        return new Promise((resolve, reject) => {
            request(`/api/treatment-sessions/${filter.sessionId}/sections`,{
                method: 'get'
            }).then((r)=>{
                resolve(r)
            }).catch(()=>{
                resolve(this.defaultList.filter((item)=>{
                    return item.sessionId === filter.sessionId
                }))
            })
        })

    }
}

class TreatmentSession {
    constructor() {
        this.body = {}

        this.defaultList= [
            // {
            //     id:1,
            //     name:'助眠引导',
            //     author:'夜听小叶子',
            //     categoryId: 1,
            //
            // },
            // {
            //     id:2,
            //     name:'放松身心',
            //     author: '桂圆妈妈',
            //     categoryId: 1,
            // }
        ]
    }

    create(body){
        return request('/api/treatment-sessions',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    getItem(id){
        return new Promise((resolve, reject) => {
            request('/api/treatment-sessions/'+id,{
                method: 'get'
            }).then((r)=>{
                resolve(r)
            }).catch(()=>{
                resolve(this.defaultList.find((item)=>{
                    return item.id === id
                }))
            })
        })
    }

    getList(filter){
        return new Promise((resolve, reject) => {
            request('/api/treatment-sessions?filter='+encodeURIComponent(filter),{
                method: 'get',
            }).then((r)=>{
                resolve(r.entities)
            }).catch(()=>{
                resolve(this.defaultList)
            })
        })
    }

    getSelfList(filter){
        return new Promise((resolve, reject) => {
            request('/api/treatment-sessions/self?filter='+encodeURIComponent(filter),{
                method: 'get',
            }).then((r)=>{
                resolve(r.entities)
            }).catch(()=>{
                resolve(this.defaultList)
            })
        })
    }

    getSelfInstancesList(filter){
        return new Promise((resolve, reject) => {
            request('/api/session-instances?filter='+encodeURIComponent(filter),{
                method: 'get',
            }).then((r)=>{
                resolve(r.entities)
            }).catch(()=>{
                resolve(this.defaultList)
            })
        })
    }

    update(body){
        let id = body.id
        delete body.id
        return request('/api/treatment-sessions/'+id,{
            method: 'PATCH',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    delete(){

    }
}

class User{
    constructor() {
        this.user = null
        this.token = null
    }

    getValidation(body){
        return request(`/api/validations/by-email`,{
            method: 'put',
            headers:{
                'Content-Type':'text/plain'
            },
            body:body
        })
    }

    getToken(){
        let token = sessionStorage.getItem('token')
        if(this.token || token){
            Authorization = this.token || token
            // document.cookie = this.token || token
        }
        return   this.token || token
    }



    getUserInfo(){
        return new Promise((resolve, reject) => {
            if(!this.user){
                this.getSelf().then((result)=>{
                    console.log(result)
                    this.user = result
                    resolve(result)
                }).catch((e)=>{
                    reject(e)
                })
            } else {
                resolve(this.user )
            }
        })

    }

    getSelf(){
        return request('/api/users/self',{
            method: 'get'
        })
    }

    register(body){
        return new Promise((resolve, reject) => {
            request('/api/users',{
                method: 'post',
                headers:{
                    'Content-Type':'application/json'
                },
                body: JSON.stringify(body)
            }).then((result)=>{
                resolve(result)
            }).catch((e)=>{
                reject(e)
            })
        })
    }

    login(body,isSave){
        return new Promise((resolve, reject) => {
            request('/api/sessions',{
                method: 'post',
                headers:{
                    'Content-Type':'application/json'
                },
                body: JSON.stringify(body)
            }).then((result)=>{
                if(result.identity){
                    Authorization = this.token = result.identity
                    sessionStorage.removeItem('token')
                    // if(isSave){
                        sessionStorage.setItem('token',this.token)
                    // }
                }
                resolve(result)
            }).catch((e)=>{
                reject(e)
            })
        })

    }

    logout(){
        sessionStorage.removeItem('token')
        this.token = null
        return request('/api/sessions/self',{
            method: 'delete',
        })
    }
}

class Language {
    constructor() {
    }
    getList(){
        return request('/api/languages',{
            method: 'get'
        })
    }
}

class Category{
    constructor() {
        this.defaultList = [
            {
                name:'轻松',
                id:1
            }
        ]
    }
    getList(){
        return new Promise((resolve, reject) => {
            request('/api/categories',{
                method: 'get'
            }).then((r)=>{
                resolve(r.entities)
            }).catch(()=>{
                resolve(this.defaultList)
            })
        })

    }
}

class SectionFlow {
    constructor() {

    }

    put(id,body){
        return request(`/api/treatment-sessions/${id}/section-flows`,{
            method: 'PUT',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    getList(id){
        return new Promise((resolve, reject) => {
            request(`/api/treatment-sessions/${id}/section-flows`,{
                method: 'GET',
            }).then((r)=>{
                resolve(r)
            }).catch(()=>{
                resolve([])
            })
        })
    }
}

class Question {
    constructor() {
    }
    getList(id){
        return request(`/api/treatment-sessions/${id}/questionnaires`,{
            method: 'GET'
        })
    }

    get(id){
        return request(`/api/questionnaires/${id}`,{
            method: 'get'
        })
    }

    create(body){
        return request('/api/questionnaires',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    update(id,body){
        return request(`/api/questionnaires/${id}`,{
            method: 'put',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    submit(body){
        return request('/api/questionnaire-instances',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    updateList(id, body) {
        return request(`/api/treatment-sessions/${id}/questionnaires`,{
            method: 'put',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }
}

class QuestionnaireInstances{
    constructor() {
    }

    getList(params){
        return request(`/api/questionnaire-instances?filter=${encodeURIComponent(params)}`,{
            method: 'get'
        })
    }

    create(body){
        return request('/api/questionnaire-instances',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }
}

class SessionInstances{
    constructor() {

    }

    create(body){
        return request('/api/session-instances',{
            method: 'post',
            headers:{
                'Content-Type':'application/json'
            },
            body: JSON.stringify(body)
        })
    }

    getList(sessionId){
        // GET /api/session-instances?filter={"sessionId":"...."}
        return request('/api/session-instances?filter='+encodeURIComponent(JSON.stringify({
            sessionId: sessionId
        })),{
            method: 'get'
        })
    }
}
